package com.paradise.ytj.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.Toast;

import com.paradise.ytj.R;
import com.paradise.ytj.bean.AgreeEvent;
import com.paradise.ytj.bean.Constant;
import com.paradise.ytj.bean.FinishEvent;
import com.paradise.ytj.bean.HangupEvent;
import com.paradise.ytj.bean.MenuVideoEvent;
import com.paradise.ytj.bean.MessageEvent;
import com.paradise.ytj.bean.VideoBackEvent;
import com.paradise.ytj.bean.VisiableEvent;
import com.paradise.ytj.fragment.VideoFragment;
import com.paradise.ytj.fragment.WaitFragment;
import com.paradise.ytj.helper.RecordDao;
import com.paradise.ytj.utils.ActivityUtils;
import com.paradise.ytj.utils.CameraUtils;
import com.paradise.ytj.utils.DialogUtils;
import com.paradise.ytj.utils.HomeListener;
import com.paradise.ytj.utils.SpUtils;
import com.paradise.api.FaceCall;
import com.paradise.api.FacePhone;
import com.paradise.api.FacephoneListener;
import com.paradise.api.FacephonePreferences;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.linphone.core.LinphoneCall;
import org.linphone.core.LinphoneCore;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;


public class VideoActivity extends FragmentActivity implements FacephoneListener.FacephoneCallStateListener {

    private WaitFragment waitFragment;
    private VideoFragment videoFragment;
    private String phone;
    private String inout;
    private String object;
    private Bundle bundle;
    private Chronometer cTime;
    public static boolean isFirstBack = true;
    private Context context;
    private LinphoneCall oldCall;
    public boolean isTerminate = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initConfig();
        setContentView(R.layout.activity_video);
        initVar();
        initView();
        initData();
        initListener();
    }

    private void initConfig() {
        //去除title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉Activity上面的状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void initVar() {
        context = VideoActivity.this;
        ActivityUtils.addActivity(VideoActivity.this);
        registerHomeListener();

    }

    private void initView() {
        EventBus.getDefault().register(this);
        cTime = (Chronometer) findViewById(R.id.c_time);
        cTime.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer cArg) {
                long time = System.currentTimeMillis() - cArg.getBase();
                Date d = new Date(time);
                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.US);
                sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
                cTime.setText(context.getResources().getString(R.string.call_duration) + sdf.format(d));
            }
        });
        cTime.setBase(System.currentTimeMillis());
        cTime.start();
    }

    private void initData() {

        Intent intent = getIntent();
        inout = intent.getStringExtra("inout");
        object = intent.getStringExtra("object");
        phone = intent.getStringExtra("phone");
        bundle = new Bundle();
        bundle.putString("inout", inout);
        bundle.putString("object", object);
        bundle.putString("phone", phone);
        if (inout == null) {
            inout = "out";
        }
        if (object == null) {
            object = "";
        }
        if (inout.equals("out")) {
            FacephonePreferences.instance().setInitiateVideoCall(true);
            FaceCall.instance().call(context,
                    phone,
                    FacephonePreferences.instance().getAccountDisplayName(FacephonePreferences.instance().getAccountCount() - 1));
            if (waitFragment == null) {
                waitFragment = new WaitFragment();
            }
            waitFragment.setArguments(bundle);
            commitFragment(waitFragment);
            SpUtils.putString(context, Constant.METHOD_NAME, Constant.METHOD_DEFAULT);

        } else if (inout.equals("in")) {
            boolean auto = intent.getBooleanExtra("auto", false);
            if (auto) {
                FaceCall.instance().acceptCall();
                switchVideo();
            } else {
                if (waitFragment == null) {
                    waitFragment = new WaitFragment();
                }
                waitFragment.setArguments(bundle);
                commitFragment(waitFragment);
            }
        }
    }

    private void initListener() {
        FacePhone.instance().addCallStateListener(this);
    }

    @Override
    public void callState(LinphoneCore linphoneCore, LinphoneCall linphoneCall, LinphoneCall.State state, String s, boolean b, boolean b1) {
        if (oldCall == null) {
            oldCall = linphoneCall;
        }

        //通话成功状态
        if (state.equals(LinphoneCall.State.Connected)) {
            Log.e("para", "Connected");
            CameraUtils.stopCamera();
            if (CameraUtils.getNumber() == 0) {
                return;
            }
            switchVideo();
        } else if (state.equals(LinphoneCall.State.Error)) {
            Log.e("para", "Error");
            String reason = linphoneCall.getErrorInfo().getReason().toString();
            isTerminate = false;
            if (reason.equals("NotAnswered")) {
                Toast.makeText(context, R.string.NotAnswered, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("Declined")) {
                Toast.makeText(context, R.string.Declined, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("TemporarilyUnavailable")) {
                Toast.makeText(context, R.string.TemporarilyUnavailable, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("NotFound")) {
                Toast.makeText(context, R.string.NotFound, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("IOError")) {
                Toast.makeText(context, R.string.IOError, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("None")) {
                Toast.makeText(context, R.string.None, Toast.LENGTH_SHORT).show();

            }
            finish();
        } else if (state.equals(LinphoneCall.State.StreamsRunning)) {

        } else if (state.equals(LinphoneCall.State.CallEnd)) {
            Log.e("para", "CallEnd");
            if (!linphoneCall.getRemoteAddress().getUserName().equals(oldCall.getRemoteAddress().getUserName())) {
                return;
            }
            String reason = linphoneCall.getErrorInfo().getReason().toString();
            isTerminate = false;
            if (reason.equals("NotAnswered")) {
                Toast.makeText(context, R.string.NotAnswered, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("Declined")) {
                Toast.makeText(context, R.string.Declined, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("TemporarilyUnavailable")) {
                Toast.makeText(context, R.string.TemporarilyUnavailable, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("NotFound")) {
                Toast.makeText(context, R.string.NotFound, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("IOError")) {
                Toast.makeText(context, R.string.IOError, Toast.LENGTH_SHORT).show();
            } else if (reason.equals("None")) {
                Toast.makeText(context, R.string.None, Toast.LENGTH_SHORT).show();

            }
            //通话结束状态
            finish();
        } else if (state.equals(LinphoneCall.State.CallReleased)) {
            Log.e("para", "CallReleased");
            finish();
        }
    }


    /**
     * 提交fragment事务
     *
     * @param fragment 显示的fragment
     */

    private void commitFragment(Fragment fragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fl_video, fragment);
        transaction.commit();
    }


    @Override
    protected void onDestroy() {
        ActivityUtils.removeActivity(VideoActivity.this);
        mHomeWatcher.stopWatch();
        FacePhone.instance().removeCallStateListener();
        MessageEvent messageEvent = new MessageEvent();
        EventBus.getDefault().post(messageEvent);
        EventBus.getDefault().unregister(this);
        FaceCall.instance().terminateCurrentCall();
        long sysTime = System.currentTimeMillis();//获取系统时间
        CharSequence sysTimeStr = DateFormat.format("HH:mm:ss", sysTime);//时间显示格式
        Date date = new Date();
        CharSequence year = DateFormat.format("yyyy-MM-dd", date);
        String time = year.toString() + "/" + sysTimeStr.toString();
        RecordDao recordDao = new RecordDao(context);
        recordDao.add(object, phone, time, cTime.getText().toString());
        FinishEvent finishEvent = new FinishEvent();
        EventBus.getDefault().post(finishEvent);
        super.onDestroy();
    }


    /**
     * 是否切换到视频
     */
    private void switchVideo() {
        if (videoFragment == null) {
            videoFragment = new VideoFragment();
            videoFragment.setArguments(bundle);
        }
        commitFragment(videoFragment);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        VisiableEvent visiableEvent = new VisiableEvent();
        if (keyCode == 82) {
            visiableEvent.setMenu(true);
        } else {
            visiableEvent.setMenu(false);
        }
        EventBus.getDefault().post(visiableEvent);
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        Log.e("para","onBackPressed");
        VideoBackEvent event = new VideoBackEvent();
        EventBus.getDefault().post(event);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getAgree(AgreeEvent agreeEvent) {
        FaceCall.instance().acceptCall();
        switchVideo();

    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void getHangup(HangupEvent hangupEvent) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(500);
                if (isTerminate == true) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                            Toast.makeText(context, R.string.call_finish, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

    private HomeListener mHomeWatcher;

    /**
     * //     * 注册Home键的监听
     * //
     */
    private void registerHomeListener() {
        mHomeWatcher = new HomeListener(this);
        mHomeWatcher.setOnHomePressedListener(new HomeListener.OnHomePressedListener() {

            @Override
            public void onHomePressed() {
                DialogUtils.removeALLDialog();
                Toast.makeText(context, R.string.home_key_hint, Toast.LENGTH_SHORT).show();
                FaceCall.instance().terminateCurrentCall();
                ActivityUtils.removeALLActivity();
            }

            @Override
            public void onHomeLongPressed() {

            }
        });
        mHomeWatcher.startWatch();
    }
}